package com.journaldev.spring.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import com.journaldev.spring.model.Patient;
import com.journaldev.spring.model.Prescription;

@Transactional
public class PrescriptionDAOImpl implements PrescriptionDAO {
	
	private static final Logger logger = LoggerFactory.getLogger(DistrictDAOImpl.class);

	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sf){
		this.sessionFactory = sf;
	}

	@Override
	public void addPrescription(Prescription p) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		session.persist(p);
		logger.info("Prescription saved successfully, Prescription Details="+p);
	}

	@Override
	public void updatePrescription(Prescription p) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		session.update(p);
		logger.info("Prescription updated successfully, Prescription Details="+p);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Prescription> listPrescription() {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		List<Prescription> prescriptionList = session.createQuery("from Prescription").list();
		for(Prescription p : prescriptionList){
			logger.info("Prescription List::"+p);
		}
		return prescriptionList;
	}

	@Override
	public Prescription getPrescriptionById(int id) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();		
		Prescription p = (Prescription) session.get(Prescription.class, new Integer(id));
		logger.info("Prescription loaded successfully, Prescription details="+p);
		return p;
	}

	@Override
	public void removePrescription(Prescription p) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		//Prescription p = (Prescription) session.get(Prescription.class, new Integer(id));
		if(null != p){
			//session.update(p);
			session.delete(p);
		}
		logger.info("Prescription deleted successfully, Prescription details="+p);
	}

}
